/*
 * @Description: 全宗上下文
 * @Author: Rfan
 * @Date: 2022-01-08 16:30:05
 * @LastEditTime: 2022-07-11 17:25:08
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import { message } from 'antd';
import { addFond, deleteFond, editFond, fetchFondsListByUnitId } from '@/api/fonds';
import { FondsReducer } from '../reducers/FondsReducer';
import {
  ADD_FONT,
  DELETE_FONT,
  EDIT_FONT,
  LOADING,
  SET_FOND_LIST,
  SET_QUERY,
  SET_SELECT_FOND,
  SET_SELECT_UNIT
} from '../constants';

const initialState = {
  // 当前选中的项目
  selectUnit: {},
  selectFondId: 0,

  // 添加弹窗
  dialog: {
    visible: false
  },

  // 编辑弹窗
  editDialog: {
    visible: false,
    current: {}
  },

  // 列表相关
  listQuery: {
    pageNo: 1,
    pageSize: 10,
    param: {
      comment: '',
      fondCode: '',
      fondName: ''
    }
  },
  loading: false,
  list: []
};

const FondContext = createContext();

const FondContextProvider = (props) => {
  const [state, dispatch] = useReducer(FondsReducer, initialState);

  const actions = {
    /**
     * @description: 设置选中的单位
     * @param {object} data 选中的单位对象
     */
    setSelectUnit(data) {
      dispatch({ type: SET_SELECT_UNIT, data });
    },

    /**
     * @description: 设置选中的全宗
     * @param {number} id 选中的全宗ID
     */
    setSelectFond(id) {
      dispatch({ type: SET_SELECT_FOND, id });
    },

    /**
     * @description: 新增全宗
     * @param {object} data 全宗相关信息
     */
    onAddFond(data) {
      return new Promise((resolve, reject) => {
        addFond(data)
          .then((res) => {
            dispatch({ type: ADD_FONT, data: res.data });
            resolve(res.data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /**
     * @description: 新增全宗
     * @param {object} data 全宗相关信息
     */
    editFondFunc(data) {
      return new Promise((resolve, reject) => {
        editFond(data)
          .then((res) => {
            // dispatch({ type: EDIT_FONT, data: res.data });
            message.success('编辑成功');
            resolve(res.data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    onDeleteFond(id) {
      deleteFond(id).then(() => {
        dispatch({ type: DELETE_FONT, id });
      });
    },

    setListQuery(info) {
      dispatch({ type: SET_QUERY, info });
    },

    /**
     * @description:根据单位ID获取全宗列表
     */
    async fetchData() {
      dispatch({ type: LOADING });
      // const res = await fetchFondsList(state.listQuery);
      const res = await fetchFondsListByUnitId(state.selectUnit.id); // unitId 暂时写死为2
      const { data } = res;
      dispatch({ type: SET_FOND_LIST, data });
    }
  };

  // watch选中的单位来加载全宗
  useEffect(() => {
    if (state.selectUnit?.id) {
      actions.fetchData();
    }
  }, [state.selectUnit]);

  return (
    <FondContext.Provider value={{ ...state, ...actions }}>{props.children}</FondContext.Provider>
  );
};

export const useFondContext = () => {
  return useContext(FondContext);
};

export { FondContext, FondContextProvider };
